<template>
    <div>
        <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false" width="70%">
            <el-form :model="dataForm" :rules="dataRule" ref="dataForm"  :label-width="$i18n.locale === 'en-US' ? '120px' : '120px'">
                <el-row :gutter="20">
                    <el-col :xs="24" :lg="colConfig">
                        <el-form-item label="预警名称" prop="name">
                            <el-input v-model="dataForm.name" placeholder="预警名称"></el-input>
                        </el-form-item>
                        <el-form-item prop="remars" label="预警详情">
                            <!-- 富文本编辑器, 容器 -->
                            <div id="J_quillEditor"></div>
                            <!-- 自定义上传图片功能 (使用element upload组件) -->
                            <el-upload
                                    :action="uploadUrl"
                                    :show-file-list="false"
                                    :before-upload="uploadBeforeUploadHandle"
                                    :on-success="uploadSuccessHandle"
                                    style="display: none;">
                                <el-button ref="uploadBtn" type="primary" size="mini">{{ $t('upload.button') }}</el-button>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="项目名称" prop="projectName">
                            <el-input v-model="dataForm.projectName" placeholder="项目名称">
                                <el-button slot="append" icon="el-icon-circle-plus" @click="selectShow" ref="searchId" @refreshDataList="getDataList()"></el-button>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="预警类型" prop="warningType">
                                <el-select
                                        v-model="dataForm.warningType"
                                        clearable
                                        placeholder="请选择预警类型"
                                >
                                    <el-option
                                            v-for="item in warningTypeoptions"
                                            :key="item.dictCode"
                                            :label="item.dictName"
                                            :value="item.dictCode"
                                    >
                                    </el-option>
                                </el-select>
                        </el-form-item>
                        <el-form-item label="状态" prop="status" size="mini">
                            <el-radio-group v-model="dataForm.status">
                                <el-radio :label="0">停用</el-radio>
                                <el-radio :label="1">正常</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="项目id" hidden prop="projectId">
                    <el-input v-model="dataForm.projectId" placeholder="项目id"></el-input>
                </el-form-item>
                <el-form-item label="项目编码" hidden prop="projectCode">
                    <el-input v-model="dataForm.projectCode"   placeholder="项目编码"></el-input>
                </el-form-item>
                <el-form-item label="预警编码" hidden prop="code">
                    <el-input v-model="dataForm.code" placeholder="预警编码"></el-input>
                </el-form-item>
            </el-form>
            <template slot="footer">
                <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
                <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
            </template>
        </el-dialog>
        <select-project v-if="selectVisible" ref="selectProject" @refreshDataList="getDataList()"></select-project>
    </div>
</template>

<script>
import Bus from '@/api/bus.js'
import debounce from 'lodash/debounce'
import SelectProject from '@/views/modules/basic/bimproject-select'
import Cookies from 'js-cookie'
import 'quill/dist/quill.snow.css'
import Quill from 'quill'
export default {
  data () {
    return {
      colConfig: 1, // 列配置 1 2列
      visible: false,
      selectVisible: false,
      dataForm: {
        id: '',
        code: '',
        name: '',
        remars: '',
        projectId: '',
        projectCode: '',
        projectName: '',
        warningType: '0',
        deptId: '',
        status: 1,
        creator: '',
        createDate: '',
        updater: '',
        updateDate: ''
      },
      quillEditor: null,
      quillEditorToolbarOptions: [
        ['bold', 'italic', 'underline', 'strike'],
        ['blockquote', 'code-block', 'image'],
        [{ 'header': 1 }, { 'header': 2 }],
        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
        [{ 'script': 'sub' }, { 'script': 'super' }],
        [{ 'indent': '-1' }, { 'indent': '+1' }],
        [{ 'direction': 'rtl' }],
        [{ 'size': ['small', false, 'large', 'huge'] }],
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
        [{ 'color': [] }, { 'background': [] }],
        [{ 'font': [] }],
        [{ 'align': [] }],
        ['clean']
      ],
      uploadUrl: '',
      getDicListURL: '/sys/dict/type/',
      warningTypeoptions: ''
    }
  },
  created () {
    this.colConfig = 24 / this.colConfig
  },
  computed: {
    dataRule () {
      var validateContent = (rule, value, callback) => {
        if (this.quillEditor.getLength() <= 1) {
          return callback(new Error(this.$t('validate.required')))
        }
        callback()
      }
      return {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        remars: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' },
          { validator: validateContent, trigger: 'blur' }
        ],
        warningType: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        status: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]

      }
    }
  },
  components: {
    SelectProject
  },
  mounted: function () {
    // 用$on事件来接收参数
    Bus.$on('val', (data) => {
      if (data != null) {
        var strs = data.split(',') // 字符分割
        this.dataForm.projectId = strs[0]
        this.dataForm.projectCode = strs[1]
        this.dataForm.projectName = strs[2]
      }
    })
  },
  methods: {
    init () {
      this.visible = true
      this.getWarningType()
      this.$nextTick(() => {
        if (this.quillEditor) {
          this.quillEditor.deleteText(0, this.quillEditor.getLength())
        } else {
          this.quillEditorHandle()
        }
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    // 获取预警类别信息
    getWarningType () {
      this.$http.get(this.getDicListURL + 'warningType').then(({ data: res }) => {
        if (res.code !== 0) {
          return false
        }
        this.warningTypeoptions = {
          ...this.warningTypeoptions,
          ...res.data.list
        }
      }).catch(() => { })
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/demo:tbwarninginfo/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return false
        }
        this.dataForm = res.data
        this.quillEditor.root.innerHTML = this.dataForm.remars
      }).catch(() => {
      })
    },
    // 富文本编辑器
    quillEditorHandle () {
      this.quillEditor = new Quill('#J_quillEditor', {
        modules: {
          toolbar: this.quillEditorToolbarOptions
        },
        theme: 'snow'
      })
      // 自定义上传图片功能 (使用element upload组件)
      this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/sys/oss/upload?token=${Cookies.get('studyToken')}`
      this.quillEditor.getModule('toolbar').addHandler('image', () => {
        this.$refs.uploadBtn.$el.click()
      })
      // 监听内容变化，动态赋值
      this.quillEditor.on('text-change', () => {
        this.dataForm.remars = this.quillEditor.root.innerHTML
      })
    },
    // 上传图片之前
    uploadBeforeUploadHandle (file) {
      if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
        this.$message.error('只支持jpg、png、gif格式的图片！')
        return false
      }
    },
    // 上传图片成功
    uploadSuccessHandle (res, file, fileList) {
      if (res.code !== 0) {
        return false
      }
      this.quillEditor.insertEmbed(this.quillEditor.getSelection().index, 'image', res.data.src)
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http[!this.dataForm.id ? 'post' : 'put']('/demo:tbwarninginfo/', this.dataForm
        ).then(({ data: res }) => {
          if (res.code !== 0) {
            return false
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {
        })
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    // 按钮点击事件
    selectShow () {
      this.selectVisible = true
      this.$nextTick(() => {
        this.$refs.selectProject.init()
      })
    }
  }
}
</script>
